import router from "@/router";
import NProgress from "@/utils/nprogress";
import { whiteRouterList } from "@/router/index";
import { TOKEN_KEY,Mobile_TOKEN_KEY } from "@/enums/CacheEnum";

// 白名单路由
const whiteList = whiteRouterList.map((item) => item.path);
export function setupPermission() {
	router.beforeEach(async (to, from, next) => {
		const isMobile = window.matchMedia('(max-width: 768px)').matches;
		console.log(isMobile,"isMobile");
		if (!isMobile) {
			const hasToken = localStorage.getItem(TOKEN_KEY);
			
			NProgress.start();
			if (hasToken && to.matched.length !== 0) {
				if (to.path === "/login") {
					next({ path: "/" });
					NProgress.done();
				} else {
					next();
					NProgress.done();
				}
			}else {
				// 未登录可以访问白名单页面
				if (whiteList.indexOf(to.path) !== -1) {
					if (whiteList.indexOf(to.path) == 1) {
						next(`/login`);
						NProgress.done();
					}else{
						next();
					}
				} else {
					next(`/login`);
					NProgress.done();
				}
			}
		}else{
			const hasToken = localStorage.getItem(Mobile_TOKEN_KEY);		
			NProgress.start();
			if (hasToken && to.matched.length !== 0) {
				if (to.path === "/mobileLogin") {
					next({ path: "/mobile" });
					NProgress.done();
				}if (to.path === "/login") {
					next({ path: "/mobileLogin" });
					NProgress.done();
				} else {
					next();
					NProgress.done();
				}
			}else {
				// 未登录可以访问白名单页面
				if (whiteList.indexOf(to.path) !== -1) {
					if (whiteList.indexOf(to.path) == 0) {
						next(`/mobileLogin`);
						NProgress.done();
					}else{
						next();
					}
				} else {
					next(`/mobileLogin`);
					NProgress.done();
				}
			}
		}

	});

	router.afterEach(() => {
		NProgress.done();
	});
}
